/*
 * Copyright 2014 Hieu Rocker
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.rockerhieu.emojicon;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.rockerhieu.emojicon.EmojiconsFragment.OnEmojiconBackspaceClickedListener;
import com.rockerhieu.emojicon.EmojiconsFragment.RepeatListener;
import com.rockerhieu.emojicon.emoji.Emojicon;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Hieu Rocker (rockerhieu@gmail.com)
 */
public class EmojiconGridFragment extends Fragment implements AdapterView.OnItemClickListener {
    private OnEmojiconClickedListener mOnEmojiconClickedListener;
    private  OnEmojiconBackspaceClickedListener mOnEmojiconBackspaceClickedListener;
    private EmojiconRecents mRecents;
    private Emojicon[] mData;
    private boolean mUseSystemDefault = false;

    private static final String USE_SYSTEM_DEFAULT_KEY = "useSystemDefaults";
    private List<View> mViewList = new ArrayList<View>();
    
	private LinearLayout layout_point;

	private ArrayList<ImageView> pointViews;
	private int current = 0;
	ViewPager mViewPager;
    private int  pagenum=20 ;
    protected static EmojiconGridFragment newInstance(Emojicon[] emojicons, EmojiconRecents recents) {
        return newInstance(emojicons, recents, false);
    }

    protected static EmojiconGridFragment newInstance(Emojicon[] emojicons, EmojiconRecents recents, boolean useSystemDefault) {
        EmojiconGridFragment emojiGridFragment = new EmojiconGridFragment();
        Bundle args = new Bundle();
        args.putSerializable("emojicons", emojicons);
        args.putBoolean(USE_SYSTEM_DEFAULT_KEY, useSystemDefault);
        emojiGridFragment.setArguments(args);
        emojiGridFragment.setRecents(recents);
        return emojiGridFragment;
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.emojicon_gridgroup, container, false);
    }
   
    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
    	 
          mViewList.clear();
    	 mViewPager= (ViewPager) view.findViewById(R.id.emojis_gridpager);
    	layout_point = (LinearLayout) view.findViewById(R.id.iv_image);
    	
    	Object[] o = (Object[]) getArguments().getSerializable("emojicons");
        mData = Arrays.asList(o).toArray(new Emojicon[o.length]);
        int page=0;
    	if(mData.length%pagenum==0)
    		page=mData.length/pagenum;
    	else
    		page=mData.length/pagenum+1;
    	
    	for(int n=0;n<page;n++){
    		int start = n * pagenum;
			int end = n * pagenum + pagenum;
			end = end > mData.length? mData.length : end;
			
    		ArrayList<Emojicon> emojicons=new ArrayList<Emojicon>();
	    	for(int i=start;i<end;i++){
	    		emojicons.add(mData[i]);
	    	}
	    	Emojicon m=new Emojicon("");
	    	emojicons.add(m);
	    	View   mInflater = getActivity().getLayoutInflater().inflate(R.layout.emojicon_grid, null);
	    	GridView gridView =(GridView) mInflater.findViewById(R.id.Emoji_GridView);
	        gridView.setAdapter(new EmojiAdapter(view.getContext(), emojicons, mUseSystemDefault));
	        gridView.setOnItemClickListener(this);
	        mViewList.add(gridView);
    	}
    	initData();
        Init_Point();
       
    }
    
    private void initData(){
    	 mViewPager.setAdapter(new MyPagerAdapter());
         mViewPager.setCurrentItem(0);
         mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

 			@Override
 			public void onPageSelected(int arg0) {
 				draw_Point(arg0);
 			}

 			@Override
 			public void onPageScrolled(int arg0, float arg1, int arg2) {

 			}

 			@Override
 			public void onPageScrollStateChanged(int arg0) {

 			}
 		});
    }
	public void draw_Point(int index) {
		for (int i = 0; i < pointViews.size(); i++) {
			if (index == i) {
				pointViews.get(i).setBackgroundResource(R.drawable.ic_gz_change22);
			} else {
				pointViews.get(i).setBackgroundResource(R.drawable.ic_gz_change11);
			}
		}
	}
	private void Init_Point() {

		pointViews = new ArrayList<ImageView>();
		ImageView imageView;
		for (int i = 0; i < mViewList.size(); i++) {
			imageView = new ImageView(getActivity());
			imageView.setBackgroundResource(R.drawable.ic_gz_change11);
			LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
					new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT));
			layoutParams.leftMargin = 10;
			layoutParams.rightMargin = 10;
			layoutParams.width = 15;
			layoutParams.height = 15;
			layout_point.addView(imageView, layoutParams);
			if (i == 0) {
				imageView.setBackgroundResource(R.drawable.ic_gz_change22);
			}
			pointViews.add(imageView);

		}
	}

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("emojicons", mData);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof OnEmojiconClickedListener) {
            mOnEmojiconClickedListener = (OnEmojiconClickedListener) activity;
        } else if (getParentFragment() instanceof OnEmojiconClickedListener) {
            mOnEmojiconClickedListener = (OnEmojiconClickedListener) getParentFragment();
        } else {
            throw new IllegalArgumentException(activity + " must implement interface " + OnEmojiconClickedListener.class.getSimpleName());
        }
        
        if (getActivity() instanceof OnEmojiconBackspaceClickedListener) {
            mOnEmojiconBackspaceClickedListener = (OnEmojiconBackspaceClickedListener) getActivity();
        } else if(getParentFragment() instanceof  OnEmojiconBackspaceClickedListener) {
            mOnEmojiconBackspaceClickedListener = (OnEmojiconBackspaceClickedListener) getParentFragment();
        } else {
            throw new IllegalArgumentException(activity + " must implement interface " + OnEmojiconBackspaceClickedListener.class.getSimpleName());
        }
    }

    @Override
    public void onDetach() {
        mOnEmojiconClickedListener = null;
        super.onDetach();
    }

    @SuppressLint("NewApi")
	@Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        try {
            if(0!=(Integer)view.getTag(R.id.tag_second)){
                view.findViewById(R.id.emojicon_icon).
                setOnTouchListener(new RepeatListener(1000, 50, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                if (mOnEmojiconBackspaceClickedListener != null) {
                mOnEmojiconBackspaceClickedListener.onEmojiconBackspaceClicked(v);
                }
                }
                }));
            }
            if (mOnEmojiconClickedListener != null) {
                mOnEmojiconClickedListener.onEmojiconClicked((Emojicon) parent.getItemAtPosition(position));
            }
            if (mRecents != null) {
                mRecents.addRecentEmoji(view.getContext(), ((Emojicon) parent
                    .getItemAtPosition(position)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setRecents(EmojiconRecents recents) {
        mRecents = recents;
    }

    public interface OnEmojiconClickedListener {
        void onEmojiconClicked(Emojicon emojicon);
    }
    
    
    class MyPagerAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return mViewList.size();
        }
        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(mViewList.get(position));
        }
        
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(mViewList.get(position), 0);
            return mViewList.get(position);
        }
    }
}
